package com.hykj.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hykj.dao.productsDao;
import com.hykj.toolsbean.StringHandler;
import com.hykj.valuebean.products;
import com.jspsmart.upload.File;
import com.jspsmart.upload.Files;
import com.jspsmart.upload.SmartUpload;

public class ProductsServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String servletpath = request.getServletPath();
		if ("/products/getAllProducts".equals(servletpath)) {
			getAllProducts(request, response);
		} else if ("/products/viewProduct".equals(servletpath)) {
			getSingleProduct(request, response);
		} else if ("/admin/products/insertProduct".equals(servletpath)) {
			insertProduct(request, response);
		} else if ("/admin/listProducts".equals(servletpath)) {
			listProducts(request, response);
		} else if ("/admin/products/viewProduct".equals(servletpath)) {
			adminViewProduct(request, response);
		} else if ("/admin/products/deleteProduct".equals(servletpath)) {
			deleteProduct(request, response);
		} else if ("/products/getCategoryProducts".equals(servletpath)) {
			getCategoryProducts(request, response);
		} else if ("/admin/products/updateProduct".equals(servletpath)) {
			updateProduct(request, response);
		} else if ("/admin/products/getCategoryProducts".equals(servletpath)) {
			adminGetCategoryProducts(request, response);
		}
	}

	protected void adminGetCategoryProducts(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			productsDao productsDaoIns = new productsDao();
			String strcurrentP = request.getParameter("currentP");
			String strcurrentG = request.getParameter("currentG");
			String category = request.getParameter("category");
			String goWhich = "/hykj/admin/products/getCategoryProducts?category="
					+ category;
			List<?> productsList = productsDaoIns.getCategoryProducts(
					strcurrentP, strcurrentG, goWhich, category);

			request.setAttribute("productsList", productsList);
			request.setAttribute("pageBar", productsDaoIns.getDaoPage());

			productsDaoIns.closed();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		RequestDispatcher rd = request
				.getRequestDispatcher("/admin/products/listProducts.jsp");
		rd.forward(request, response);
	}

	protected void getAllProducts(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			productsDao productsDaoIns = new productsDao();
			productsDaoIns.setDaoPerR(5);
			String strcurrentP = request.getParameter("currentP");
			String strcurrentG = request.getParameter("currentG");
			String goWhich = "/hykj/products/getAllProducts";
			List<?> productsList = productsDaoIns.getAllProducts(strcurrentP,
					strcurrentG, goWhich);

			request.setAttribute("productsList", productsList);
			request.setAttribute("pageBar", productsDaoIns.getDaoPage());

			productsDaoIns.closed();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		RequestDispatcher rd = request
				.getRequestDispatcher("/products/products.jsp");
		rd.forward(request, response);
	}

	protected void getCategoryProducts(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			productsDao productsDaoIns = new productsDao();
			String strcurrentP = request.getParameter("currentP");
			String strcurrentG = request.getParameter("currentG");
			String category = request.getParameter("category");
			String goWhich = "/hykj/products/getCategoryProducts?category="
					+ category;
			List<?> productsList = productsDaoIns.getCategoryProducts(
					strcurrentP, strcurrentG, goWhich, category);

			request.setAttribute("productsList", productsList);
			request.setAttribute("pageBar", productsDaoIns.getDaoPage());

			productsDaoIns.closed();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		RequestDispatcher rd = request
				.getRequestDispatcher("/products/products.jsp");
		rd.forward(request, response);
	}

	protected void getSingleProduct(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Integer goodId = StringHandler.strToint(request.getParameter("goodId"));
		if (goodId != null) {
			try {
				productsDao productsDaoIns = new productsDao();
				products single = productsDaoIns.getSingleProduct(goodId);
				productsDaoIns.closed();
				if (single != null) {

					request.setAttribute("single", single);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		RequestDispatcher rd = request
				.getRequestDispatcher("/products/viewProduct.jsp");
		rd.forward(request, response);
	}

	protected void updateProduct(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		SmartUpload su = new SmartUpload();
		try {
			su.initialize(this.getServletConfig(), request, response); // ���ó��������ĳ�ʼ��
			su.setMaxFileSize(2 * 1024 * 1024); // �����ϴ��ļ��Ĵ�С
			su.upload();
			Files files = su.getFiles(); // ��ȡ�ϴ����ļ�����

			products product = new products();

			String describes = "";
			String argument = "";
			String introduction = "";
			String title = "";
			String category = "";
			String indexDir = "";
			String gifDir = "";
			String bigDir = "";
			int front = 0;

			for (int i = 0; i < files.getCount(); i++) {
				System.out.println(files.getCount() + "songsong");
				File singleFile = files.getFile(i); // ��ȡ�ϴ��ļ��ĵ����ļ�


				if (i == 0) {
					indexDir = su.getRequest().getParameter("indexDirHide");
					product.setIndexDir(indexDir);
					if (!singleFile.isMissing()) { // �жϸ��ļ��Ƿ�ѡ��
						System.out.println(indexDir);
						System.out.println("index");
						singleFile.saveAs(indexDir, File.SAVEAS_VIRTUAL); // ִ���ϴ�����
					}
				} else if (i == 1) {
					gifDir = su.getRequest().getParameter("gifDirHide");
					product.setGifDir(gifDir);
					if (!singleFile.isMissing()) { // �жϸ��ļ��Ƿ�ѡ��
						System.out.println(gifDir);
						System.out.println("gif");
						singleFile.saveAs(gifDir, File.SAVEAS_VIRTUAL); // ִ���ϴ�����
					}

				} else if (i == 2) {
					bigDir = su.getRequest().getParameter("bigDirHide");
					product.setBigDir(bigDir);
					if (!singleFile.isMissing()) { // �жϸ��ļ��Ƿ�ѡ��
						System.out.println(bigDir);
						System.out.println("big");

						singleFile.saveAs(bigDir, File.SAVEAS_VIRTUAL); // ִ���ϴ�����
					}
				}

			}

			System.out.println(su.getRequest().getParameter("indexDirHide"));
			describes = su.getRequest().getParameter("describes");
			argument = su.getRequest().getParameter("argument");
			introduction = su.getRequest().getParameter("introduction");
			title = su.getRequest().getParameter("title");
			category = su.getRequest().getParameter("category");
			front = StringHandler.strToint(su.getRequest()
					.getParameter("front"));

			product.setDescribes(describes);
			product.setArgument(argument);
			product.setIntroduction(introduction);
			product.setTitle(title);
			product.setCategory(category);
			product.setFront(front);
			product.setId(StringHandler.strToint(su.getRequest().getParameter(
					"id")));

			productsDao productsDaoIns = new productsDao();
			productsDaoIns.updateProduct(product);
			productsDaoIns.closed();

		} catch (Exception e) {
			System.out.println(e);
		}
		RequestDispatcher dispatcher = request
				.getRequestDispatcher("/admin/listProducts");
		dispatcher.forward(request, response);
	}

	protected void insertProduct(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		SmartUpload su = new SmartUpload();
		try {
			su.initialize(this.getServletConfig(), request, response); // ���ó��������ĳ�ʼ��
			su.setMaxFileSize(2 * 1024 * 1024); // �����ϴ��ļ��Ĵ�С
			su.upload();
			Files files = su.getFiles(); // ��ȡ�ϴ����ļ�����

			products product = new products();
			DateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd kk:mm");
			Date date = new Date();
			String stocktime = "";
			String describes = "";
			String argument = "";
			String introduction = "";
			String title = "";
			String category = "";
			String indexDir = "";
			String gifDir = "";
			String bigDir = "";
			int front = 0;

			for (int i = 0; i < files.getCount(); i++) {
				File singleFile = files.getFile(i); // ��ȡ�ϴ��ļ��ĵ����ļ�

				String fileType = singleFile.getFileExt(); // ��ȡ�ϴ��ļ�����չ��
				String[] type = { "JPG", "jpg", "gif", "bmp", "BMP" }; // �����ϴ��ļ�����չ��
				int place = java.util.Arrays.binarySearch(type, fileType); // �ж��ϴ��ļ��������Ƿ���ȷ

				if (place != -1) { // �ж��ļ���չ���Ƿ���ȷ
					if (!singleFile.isMissing()) { // �жϸ��ļ��Ƿ�ѡ��

						if (i == 0) {
							indexDir = "images/goods/"
									+ System.currentTimeMillis() + "."
									+ singleFile.getFileExt(); // ��ϵͳʱ����Ϊ�ϴ��ļ���ƣ������ϴ��ļ�������·��
							product.setIndexDir(indexDir);
							singleFile.saveAs(indexDir, File.SAVEAS_VIRTUAL); // ִ���ϴ�����
						} else if (i == 1) {
							gifDir = "images/goods/"
									+ System.currentTimeMillis() + "."
									+ singleFile.getFileExt(); // ��ϵͳʱ����Ϊ�ϴ��ļ���ƣ������ϴ��ļ�������·��
							product.setGifDir(gifDir);
							singleFile.saveAs(gifDir, File.SAVEAS_VIRTUAL); // ִ���ϴ�����

						} else if (i == 2) {
							bigDir = "images/goods/"
									+ System.currentTimeMillis() + "."
									+ singleFile.getFileExt(); // ��ϵͳʱ����Ϊ�ϴ��ļ���ƣ������ϴ��ļ�������·��
							product.setBigDir(bigDir);

							stocktime = dateformat.format(date);
							describes = su.getRequest().getParameter(
									"describes");
							argument = su.getRequest().getParameter("argument");
							introduction = su.getRequest().getParameter(
									"introduction");
							title = su.getRequest().getParameter("title");
							category = su.getRequest().getParameter("category");
							front = StringHandler.strToint(su.getRequest()
									.getParameter("front"));

							product.setStocktime(stocktime);
							product.setDescribes(describes);
							product.setArgument(argument);
							product.setIntroduction(introduction);
							product.setTitle(title);
							product.setCategory(category);
							product.setFront(front);

							// ����Ƿ�ɹ�������ݿ�
							productsDao productsDaoIns = new productsDao();
							productsDaoIns.insertProduct(product);
							productsDaoIns.closed();

							singleFile.saveAs(bigDir, File.SAVEAS_VIRTUAL); // ִ���ϴ�����
						}

					}

				}

			}

		} catch (Exception e) {
			System.out.println(e);
		}
		RequestDispatcher dispatcher = request
				.getRequestDispatcher("/admin/listProducts");
		dispatcher.forward(request, response);

	}

	protected void listProducts(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			productsDao productsDaoIns = new productsDao();
			String strcurrentP = request.getParameter("currentP");
			String strcurrentG = request.getParameter("currentG");
			String goWhich = "/hykj/admin/listProducts";
			List<?> productsList = productsDaoIns.getAllProducts(strcurrentP,
					strcurrentG, goWhich);

			request.setAttribute("productsList", productsList);
			request.setAttribute("pageBar", productsDaoIns.getDaoPage());

			productsDaoIns.closed();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		RequestDispatcher rd = request
				.getRequestDispatcher("/admin/products/listProducts.jsp");
		rd.forward(request, response);
	}

	protected void adminViewProduct(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		Integer goodId = StringHandler.strToint(request
				.getParameter("productId"));
		if (goodId != null) {
			try {
				productsDao productsDaoIns = new productsDao();
				products single = productsDaoIns.getSingleProduct(goodId);
				productsDaoIns.closed();
				if (single != null) {

					request.setAttribute("single", single);
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		RequestDispatcher rd = request
				.getRequestDispatcher("/admin/products/updateProduct.jsp");
		rd.forward(request, response);
	}

	/**
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void deleteProduct(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String ab = this.getServletContext().getRealPath("/");
		System.out.println(ab);
		String productId = request.getParameter("productId");
		String s = productId.substring(1, (productId.length() - 1));
		Pattern p = Pattern.compile(",");
		String[] path = p.split(s);
		System.out.println(path[0]);
		productsDao productsDaoIns = new productsDao();
		products productsIns = new products();
		for (int i = 0; i < path.length; i++) {
			try {
				productsIns = productsDaoIns.getSingleProduct(Integer
						.parseInt(path[i]));
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			String indexDir = productsIns.getIndexDir();
			String gifDir = productsIns.getGifDir();
			String bigDir = productsIns.getBigDir();
			java.io.File file = new java.io.File(
					ab + indexDir);
			if (file.exists()) {
				file.delete();
			}

			file = new java.io.File(ab
					+ gifDir);
			if (file.exists()) {
				file.delete();
			}
			file = new java.io.File(ab
					+ bigDir);
			if (file.exists()) {
				file.delete();
			}
		}

		productsDaoIns.deleteProduct(productId);
		productsDaoIns.closed();
		RequestDispatcher rd = request
				.getRequestDispatcher("/admin/listProducts");
		rd.forward(request, response);
	}

}